<template>
  <div class="edit-copyfor-item">
    <van-nav-bar class="header" left-arrow @click-left="onBack()">
      <template #title>
        <p style="font-size: 16px;color: #333333;font-weight: 400;">抄送设置</p>
      </template>
      <template #left>
        <van-icon name="arrow-left" size="18" color="#3B3938"/>
      </template>
    </van-nav-bar>
    <div class="filter-box">
      <van-search v-model="searchVal" placeholder="请输入搜索关键词" @search="onSearch" @clear="onSearch" />
    </div>
    <van-cell-group inset class="type-select-box">
      <van-cell :value="copyTypeValue.name" is-link @click="actionSheet=true">
        <template #title>
          <span class="custom-title">抄送类型<i class="require-span">*</i></span>
        </template>
      </van-cell>
    </van-cell-group>
    <van-cell-group class="copy-item-select" inset>
      <!-- 抄送人 -->
      <CustomSelectPanel ref="userList"
        v-if="copyTypeValue.id === SysFlowCopyForType.USER"
        height="100%"
        v-model="selectCopyForItem"
        :props="{text: 'name', value: 'id', disabled: copyItemDisabled}"
        :multiple="true"
        :dataList="loadSysUserData"
      />
      <!-- 抄送部门 -->
      <CustomCascaderPanel ref="deptList"
        v-if="copyTypeValue.id === SysFlowCopyForType.DEPT"
        v-model="selectCopyForItem" :options="deptTree"
        :props="{text: 'name', value: 'id', disabled: copyItemDisabled}"
        :multiple="true"
        :filter="filterListItem"
      />
      <!-- 抄送角色 -->
      <CustomSelectPanel ref="dataList"
        v-if="copyTypeValue.id === SysFlowCopyForType.ROLE"
        height="100%"
        v-model="selectCopyForItem"
        :props="{text: 'name', value: 'id', disabled: copyItemDisabled}"
        :multiple="true"
        :dataList="roleList"
        :filter="filterListItem"
      />
      <!-- 抄送岗位 / 审批人部门岗位 / 审批人同级部门岗位 / 审批人上级部门岗位 -->
      <CustomSelectPanel ref="dataList"
        v-if="[
          SysFlowCopyForType.POST,
          SysFlowCopyForType.SELF_DEPT_POST,
          SysFlowCopyForType.SLIBING_DEPT_POST,
          SysFlowCopyForType.UP_DEPT_POST].indexOf(copyTypeValue.id) !== -1
        "
        height="100%"
        v-model="selectCopyForItem"
        :props="{text: 'name', value: 'id', disabled: copyItemDisabled}"
        :multiple="true"
        :dataList="postList"
        :filter="filterListItem"
      />
      <!-- 指定部门岗位 -->
      <CustomCascaderPanel ref="deptPostList"
        v-if="copyTypeValue.id === SysFlowCopyForType.DEPT_POST"
        v-model="selectCopyForItem" :options="deptPostTree"
        :props="{text: 'name', value: 'id', disabled: 'disabled', showCheckbox: 'showCheckbox', disabled: copyItemDisabled}"
        :multiple="true"
        :filter="filterListItem"
      />
    </van-cell-group>
    <!-- 抄送类型弹窗 -->
    <van-action-sheet v-model="actionSheet" :actions="copyTypeList" @select="onSelectType" cancel-text="取消"/>
    <div class="menu-box">
      <van-button class="recet-btn" type="default"
        @click="resetClick"
      >
        重选
      </van-button>
      <van-button class="confirm-btn"
        :disabled="
          selectCopyForItem.length <= 0 &&
          copyTypeValue.id !== SysFlowCopyForType.SELF_DEPT_LEADER &&
          copyTypeValue.id !== SysFlowCopyForType.UP_DEPT_LEADER
        "
        @click="confirmClick"
      >
        确定{{ selectCopyForItem.length > 0 ? (' (' + selectCopyForItem.length + ')') : '' }}
      </van-button>
    </div>
  </div>
</template>
<script>
import { treeDataTranslate } from '@/utils';
import { SysCommonBizController } from '@/api';
import CustomCascaderPanel from '@/components/CustomCascaderPanel/index.vue';
import CustomSelectPanel from '@/components/CustomSelectPanel/index.vue';
export default {
  name: 'copySet',
  components: {
    CustomCascaderPanel,
    CustomSelectPanel
  },
  props: {
    // 已选中的抄送项
    selectedData: {
      type: Object
    },
    // 角色列表
    roleList: {
      type: Array
    },
    // 部门列表
    deptList: {
      type: Array
    },
    // 岗位列表
    postList: {
      type: Array
    },
    // 部门岗位列表
    deptPostList: {
      type: Array
    }
  },
  data() {
    return {
      // 抄送类型选择弹窗是否显示
      actionSheet: false,
      // 选中的抄送数据
      selectCopyForItem: [],
      // 筛选条件
      searchVal: '',
      // 选中的过滤类型值
      copyTypeValue: {}
    }
  },
  created() {
    this.copyTypeValue = this.copyTypeList[0];
  },
  methods: {
    onBack (data) {
      this.$emit('close', data);
    },
    // 选项过滤方法
    filterListItem (data) {
      if (data == null || data.name == null) return false;
      return this.searchVal == null || this.searchVal === '' || data.name.indexOf(this.searchVal) !== -1;
    },
    // 选项是否禁用方法
    copyItemDisabled (data) {
      if (this.selectedData == null) return false;
      let selectList = this.selectedData[this.copyTypeValue.id];
      if (!Array.isArray(selectList)) return false;
      return selectList.filter(item => {
        return item.id === data.id;
      }).length > 0;
    },
    // 查询
    onSearch() {
      if (this.$refs.userList) this.$refs.userList.reset();
      if (this.$refs.deptList) this.$refs.deptList.reset();
      if (this.$refs.dataList) this.$refs.dataList.reset();
      if (this.$refs.deptPostList) this.$refs.deptPostList.reset();
    },
    onSelectType (item) {
      this.actionSheet = false;
      this.copyTypeValue = item;
      this.selectCopyForItem = [];
    },
    resetClick() {
      this.selectCopyForItem = [];
    },
    // 获取选中的用户列表
    getSelectUserList() {
      return new Promise((resolve, reject) => {
        let params = {
          widgetType: 'upms_user',
          fieldName: 'loginName',
          fieldValues: (this.selectCopyForItem || []).join(',')
        }
        SysCommonBizController.viewByIds(this, params).then(res => {
          if (Array.isArray(res.data)) {
            res.data.forEach(item => {
              item.id = item.loginName;
              item.name = item.showName;
            })
            resolve(res.data);
          } else {
            resolve([]);
          }
        }).catch(e => {
          console.log(e);
          reject(e);
        });
      });
    },
    // 根据抄送类型获取抄送数据
    async buildCopyForItemList() {
      let type = this.copyTypeValue.id;
      let value;
      if (type === this.SysFlowCopyForType.USER) {
        let userList = await this.getSelectUserList();
        if (Array.isArray(userList) && userList.length > 0) {
          value = userList.map(userItem => {
            return {
              ...userItem,
              headImageUrl: this.getHeadImageUrl(userItem)
            }
          });
        }
      } else if (this.copyTypeValue.id === this.SysFlowCopyForType.SELF_DEPT_LEADER || this.copyTypeValue.id === this.SysFlowCopyForType.UP_DEPT_LEADER) {
        value = [];
      } else if (type === this.SysFlowCopyForType.DEPT) {
        let deptList = this.$refs.deptList ? this.$refs.deptList.getSelectDataList() : [];
        if (Array.isArray(deptList) && deptList.length > 0) {
          value = deptList.map(item => {
            let deptItem = null;
            if (Array.isArray(item) && item.length > 0) {
              deptItem = item[item.length - 1];
            }
            return (deptItem != null) ? {
              ...deptItem,
              name: item.map(item => item.name).join(' / ')
            } : null;
          }).filter(item => item != null);
        }
      } else if (this.copyTypeValue.id === this.SysFlowCopyForType.DEPT_POST) {
        let deptPostList = this.$refs.deptPostList ? this.$refs.deptPostList.getSelectDataList() : [];
        if (Array.isArray(deptPostList) && deptPostList.length > 0) {
          value = deptPostList.map(item => {
            let deptPostItem = null;
            if (Array.isArray(item) && item.length > 0) {
              deptPostItem = item[item.length - 1];
            }
            return deptPostItem != null ? {
              id: deptPostItem.id,
              name: item.map(item => item.name).join(' / ')
            } : null;
          }).filter(item => item != null);
        }
      } else {
        let dataList = this.$refs.dataList ? this.$refs.dataList.getSelectDataList() : [];
        if (Array.isArray(dataList) && dataList.length > 0) {
          value = dataList.map(item => {
            return {
              ...item
            }
          });
        }
      }
      return value != null ? {
        type,
        value
      } : null;
    },
    async confirmClick() {
      let formData = await this.buildCopyForItemList();
      this.onBack(formData);
    },
    // 获取用户列表
    loadSysUserData (pageNum) {
      return new Promise((resolve, reject) => {
        let params = {
          widgetType: 'upms_user',
          pageParam: {
            pageNum: pageNum,
            pageSize: 20,
            count: false
          },
          filter: {
            showName: this.searchVal
          }
        }
        SysCommonBizController.list(this, params).then(res => {
          res.data.dataList.forEach(item => {
            item.id = item.loginName;
            item.name = item.showName;
          });
          resolve({
            dataList: res.data.dataList,
            totalCount: res.data.totalCount
          })
        }).catch(e => {
          reject(e);
        })
      });
    }
  },
  computed: {
    deptTree() {
      let tempList = (this.deptList || []).map(item => {
        return {
          ...item
        }
      });
      tempList = treeDataTranslate(tempList);
      return tempList;
    },
    deptPostTree() {
      if (Array.isArray(this.deptList) && Array.isArray(this.deptPostList)) {
        let tempList = this.deptList.map(item => {
          return {
            ...item,
            isDept: true,
            showCheckbox: false
          }
        }).concat(this.deptPostList.map(deptPost => {
          return {
            ...deptPost,
            parentId: deptPost.deptId,
            id: deptPost.deptPostId,
            name: deptPost.postShowName,
            showCheckbox: true
          }
        }));
        tempList = treeDataTranslate(tempList);
        return tempList;
      }
      return [];
    },
    copyTypeList() {
      return this.SysFlowCopyForType.getList();
    }
  }
}
</script>
<style scoped>
.edit-copyfor-item {
  display: flex;
  flex-direction: column;
  background: #F6F7F9;
}
.edit-copyfor-item .header, .edit-copyfor-item .filter-box {
  flex-grow: 0;
  flex-shrink: 0;
}
.edit-copyfor-item .type-select-box {
  flex-grow: 0;
  flex-shrink: 0;
  margin-top: 16px;
  margin-bottom: 16px;
}
.edit-copyfor-item .copy-item-select {
  flex-grow: 1;
  flex-shrink: 1;
  height: 100px;
  margin-bottom: 16px;
}
.require-span {
  color: red;
  font-size: 18px;
  margin-left: 2px;
}
.menu-box {
  height: 64px;
  background-color: #ffffff;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
}
.recet-btn {
  width: 30%;
}
.confirm-btn {
  width: 60%;
  background: #ff7700;
  color: #ffffff;
}
</style>
